package com.tlgen.coopera.runner;

import com.tlgen.coopera.config.disconf.YmlPropertySourceFactory;
import com.tlgen.coopera.service.HeartBeatService;
import com.tlgen.coopera.service.RegistryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Objects;

import static com.tlgen.coopera.constant.Constants.DOWNLOAD_FILE_PATH;
import static com.tlgen.coopera.constant.Constants.READ_FILE_PATH;
import static com.tlgen.coopera.utils.FileUtils.*;

@Component
public class SpeedApplicationRunner implements ApplicationRunner {

    @Value("${spring.cloud.coopera.discovery.address}")
    private String cooperaAddress;

    @Autowired
    private HeartBeatService heartBeatService;

    @Autowired
    private ConfigurableEnvironment environment;

    @Autowired
    private RegistryService registryService;

    @Override
    public void run(ApplicationArguments args) {
        // 接收心跳信息
        heartBeatService.receive();
        // 初次启动之后要进行从远端配置中心拉取最新配置到本地
        download("http://" + cooperaAddress + "/app-local-config.yml");
        copyFile(DOWNLOAD_FILE_PATH, READ_FILE_PATH);
    }

    @Scheduled(cron = "1/1 * * * * ?")
    public void refreshConfig() {
        // 从远程配置中心拉取配置
        download("http://" + cooperaAddress + "/app-local-config.yml");
        // 判断配置内容是否发送改变
        boolean isSameContent = compareFilesByMD5(READ_FILE_PATH, DOWNLOAD_FILE_PATH);
        if (isSameContent)
            return;
        // 如果内容发生改变, 即以远程最新的为准, 将下载路径的文件替换成实际加载的文件
        copyFile(DOWNLOAD_FILE_PATH, READ_FILE_PATH);
        // 重新刷新 Bean 属性值
        PropertySource<?> propertySource = YmlPropertySourceFactory.loadProfiles();
        if (Objects.nonNull(propertySource)) {
            environment.getPropertySources().addLast(propertySource);
        }
    }

    @Scheduled(cron = "1/5 * * * * ?")
    void doRegistry() {
        // 注册服务
        registryService.doRegistry();
    }

}
